package socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author DCSGO
 * @version 1.0
 * 服务端
 * 监听9999端口，接收客户端发送的信息
 * 并回发"Hello,Client"
 */
public class SocketTCP02Server {
    public static void main(String[] args) {
        int port = 9999;
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            serverSocket = new ServerSocket(port);
            System.out.println("正在监听 " + port + " 端口...");
            socket = serverSocket.accept();
            System.out.println("有主机连接到 " + port + " 端口！");
            inputStream = socket.getInputStream();
            System.out.println("正在读取主机发送的数据...");
            int readLen;
            byte[] data = new byte[1024];
            while ((readLen = inputStream.read(data)) != -1) {
                System.out.println(new String(data, 0, readLen));
            }
            System.out.println("主机发送的数据读取完毕!");
            outputStream = socket.getOutputStream();
            System.out.println("正在向主机回传数据...");
            outputStream.write("Hello,Client".getBytes());
            socket.shutdownOutput();//设置写入结束标记 不能直接 outputStream.close()
            System.out.println("数据回传完成...");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
                if (socket != null) {
                    socket.close();
                }
                if (serverSocket != null) {
                    serverSocket.close();
                }
                System.out.println("相关资源已关闭 程序退出...");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /*
     * 正在监听 9999 端口...
     * 有主机连接到 9999 端口！
     * 正在读取主机发送的数据...
     * Hello,Server
     * 主机发送的数据读取完毕!
     * 正在向主机回传数据...
     * 数据回传完成...
     * 相关资源已关闭 程序退出...
     *
     * 进程已结束，退出代码为 0
     */
}
